﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Net;
using Excel = Microsoft.Office.Interop.Excel;
using System.Diagnostics;
using System.IO;
namespace PrinteMaster
{
    public partial class 客服窗口 : Form
    {
        public 客服窗口()
        {
            InitializeComponent();
        }
        private 主窗口 m_FatherWindow;
        //private string m_ManagerName;
        public static MySqlHelper.ManagerInfo m_ManagerInfo;
        public static 客服窗口 m_this = null;
        public static 客服窗口 getInstance() {return m_this;}
        /// <summary>
        /// 静态创建窗口的函数
        /// </summary>
        /// <param name="lpstrName"></param>
        /// <param name="window"></param>
        /// <returns></returns>
        public static 客服窗口 create(MySqlHelper.ManagerInfo info, 主窗口 window)
        {
            客服窗口 k = new 客服窗口();
            m_ManagerInfo = info;
            k.m_FatherWindow = window;
            k.Text = k.Text + " ["+ info.name + " ]";
            k.Show(window);
            m_this = k;
            //k.m_ManagerName = lpstrName;
            return k;
        }

        public void inputBossMode()
        {
            退出老板模式ToolStripMenuItem.Enabled = true;
            进入老板模式ToolStripMenuItem.Enabled = false;
            设置仅老板模式ToolStripMenuItem.Enabled = true;
            配置ToolStripMenuItem.Enabled = true;
            //查询仅老板模式ToolStripMenuItem.Enabled = true;
        }

        public void exitBossMode()
        {
            退出老板模式ToolStripMenuItem.Enabled = false;
            进入老板模式ToolStripMenuItem.Enabled = true;
            设置仅老板模式ToolStripMenuItem.Enabled = false;
            老板模式.isBossMode = false;
            配置ToolStripMenuItem.Enabled = false;
            //查询仅老板模式ToolStripMenuItem.Enabled = false;
        }

        private void 客服窗口_Load(object sender, EventArgs e)
        {
            string ip; int port;
            打印机状态.getInstance();
            Function.getSystemSetting(out ip, out port);
            if (ip == null)
            {
                //如果没有注册表项，读取默认的
                ip = textBoxIP地址.Text;
                port = Convert.ToInt32(textBox端口.Text);
            }
            else
            {
                //如果有注册表项，则设置
                textBoxIP地址.Text = ip;
                textBox端口.Text = port.ToString();
            }
        }
        /// <summary>
        /// 打印状态的枚举值
        /// </summary>
        public enum PrintState:int
        {
            /// <summary>
            /// 开始排队
            /// </summary>
            start=0,
            /// <summary>
            /// 开始打印
            /// </summary>
            print_start,
            /// <summary>
            /// 打印结束
            /// </summary>
            print_end,
            /// <summary>
            /// 队列中
            /// </summary>
            quaue

        }
        /// <summary>
        /// 打印数据结构体
        /// </summary>
        public struct PrintDate
        {
            /// <summary>
            /// 用户账号，qq号
            /// </summary>
            public string id;
            /// <summary>
            /// 用户名，注册时使用姓名
            /// </summary>
            public string name;
            /// <summary>
            /// 状态机,由PrintState 枚举值常量组成
            /// </summary>
            public PrintState state;
            /// <summary>
            /// 剩余时间：秒为单位，只有 state== PrintState.start 时有效
            /// </summary>
            public int sec;
        }
        private List<PrintDate> m_Quaue = new List<PrintDate>();
        private int lpThis = -1;
        public int sendMessage(PrintDate pd)
        {
            switch (pd.state)
            {
                case PrintState.start:
                    break;
                case PrintState.print_end:
                    break;
                case PrintState.print_start:
                    break;
                case PrintState.quaue:
                    break;
            }
            
            m_Quaue.Add(pd);
            lpThis++;
            return lpThis;
            //return 0;
        }
        /// <summary>
        /// 改变一个消息队列中的消息的状态信息
        /// </summary>
        /// <param name="pd"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool changeMessage(PrintDate pd,int id)
        {
            return false;
        }

        public bool changeMessage(PrintState state,int id)
        {
            PrintDate pd = m_Quaue[id];
            pd.state = state;
            return changeMessage(pd,id);
        }

        private void 客服窗口_FormClosing(object sender, FormClosingEventArgs e)
        {
            //打印机状态.getInstance()
        }

        private void 客服窗口_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (MessageBox.Show("真的要退出程序吗？", "退出程序", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                打印机状态.getInstance().Close();

                
                System.Environment.Exit(0);
                //打印机状态.getInstance().Close();
            }
            else
            {
                return;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            充值窗口Ex.create(m_ManagerInfo, this);
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void timer1sec_Tick(object sender, EventArgs e)
        {
            
            Ping ping = new Ping();
            PingReply result = ping.Send("localhost");
            if (result.Status != IPStatus.Success)
                labelLag.Text = "服务器连接异常!";
            else
                labelLag.Text = "Ping:" + result.RoundtripTime.ToString() + " ms";

            DataSet ds = MySqlHelper.GetDataSet(MySqlHelper.Conn, CommandType.Text, "select * from 打印机状态表", null);
            dgv.DataSource = ds.Tables[0].DefaultView;
            for (int i = 0; i < dgv.Rows.Count; i++)
            {

                if (dgv.Rows[i].Cells[2].Value.ToString() == "暂停")
                {
                    dgv.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                    dgv.Rows[i].DefaultCellStyle.ForeColor = Color.White;
                }
                else
                {
                    dgv.Rows[i].DefaultCellStyle.BackColor = Color.Green;
                    dgv.Rows[i].DefaultCellStyle.ForeColor = Color.White;
                }
            }
            DataSet req;
            DataBase.getInstance().isUserOnline(out req);
            dgv2.DataSource = req.Tables[0].DefaultView;
            //检查状态并改变颜色
            for (int i = 0; i < dgv2.Rows.Count; i++)
            {
       
                if(dgv2.Rows[i].Cells[5].Value.ToString() =="离线")
                {
                    dgv2.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                    dgv2.Rows[i].DefaultCellStyle.ForeColor = Color.White;
                }
                else
                {
                    dgv2.Rows[i].DefaultCellStyle.BackColor = Color.Green;
                    dgv2.Rows[i].DefaultCellStyle.ForeColor = Color.White;
                }
            }
        }

        private void button增加会员_Click(object sender, EventArgs e)
        {
            var c = 增加会员窗口.create(m_ManagerInfo, this);
        }

        private void 用户ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 增加用户ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var c = 增加会员窗口.create(m_ManagerInfo, this);
        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("真的要退出程序吗？", "退出程序", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                打印机状态.getInstance().Close();
                System.Environment.Exit(0);
                //打印机状态.getInstance().Close();
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            充值窗口.create(m_ManagerInfo, this);
        }

        private void 退出老板模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            exitBossMode();
        }

        private void 进入老板模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            老板模式 l = new 老板模式();
            l.ShowDialog();
        }

        private void 通用查询窗口ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            通用查询窗口 t = new 通用查询窗口();
            t.Show();
        }

        private void 系统设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            系统设置 x = new 系统设置();
            x.ShowDialog();
        }

        private void 审核验证会员ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            验证会员窗口 y = new 验证会员窗口();
            y.ShowDialog();
        }

        private void 员工账号注册ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            员工账号注册 y = new 员工账号注册();
            y.ShowDialog();
        }

        private void 添加打印机ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            添加打印机 t = new 添加打印机();
            t.ShowDialog();
        }

        private void 添加删除修改进入这里ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 不要动ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //设置连接字串
            var str = string.Format("Database='mydb';Data Source='{0}';User Id='root';Password='leopard';charset='utf8';pooling=true;port={1}",
                textBoxIP地址.Text,textBox端口.Text);
            MySqlHelper.Conn = str;
            Function.registerSysmtemSetting(textBoxIP地址.Text, Convert.ToInt32(textBox端口.Text));
        }

        private void 特殊接口删除指定员工账号ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            特殊接口_删除指定员工账号 t = new 特殊接口_删除指定员工账号();
            t.ShowDialog();
        }

        private void 特殊接口为指定会员扣费ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            特殊接口_会员扣费 k = new 特殊接口_会员扣费();
            k.ShowDialog();
        }

        private void 确认交接班收款ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            /*
            确认交接班收款 q = new 确认交接班收款();
            q.ShowDialog();
             * */
            确认客户端自助充值 q = new 确认客户端自助充值();
            q.ShowDialog();
        }

        private void 切换用户ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();//关闭当前窗口，走退出登录流程。

        }

        private void button1_Click(object sender, EventArgs e)
        {
            确认客户端自助充值 q = new 确认客户端自助充值();
            q.ShowDialog();
        }

        private void 通用查询接口ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            通用查询窗口 t = new 通用查询窗口();
            t.Show();
        }

        private void 导入数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FileDialog fd = openFileDialog1;
            fd.InitialDirectory = Application.StartupPath;
            fd.Title = "选择你的数据源(必须在第一列放置手机号并在第二列放置余额，余额可携带小数点，第一行无效):";
            fd.Filter = "Microsoft Excel文档|*.xls|Microsoft Excel文档(2003以上)|*.xlsx";
            if( fd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                return;
            
            var excelApp = new Excel.Application();
            object objOpt = System.Reflection.Missing.Value;
            var wbclass = (Excel.WorkbookClass)excelApp.Workbooks.Open(fd.FileName, objOpt, false, objOpt, objOpt, objOpt, true, objOpt, objOpt, true, objOpt, objOpt, objOpt, objOpt, objOpt);
            Excel.Worksheet sheet = null;
            Excel.Sheets sheets = wbclass.Worksheets;
            foreach (Excel.Worksheet s in sheets)
            {
                if (s.Name == "Sheet1")
                {
                    sheet = s;
                    break;
                }

            }
            var countCell = sheet.Cells.Rows.Count;

            var rang = sheet.get_Range("A1", "B"+countCell);
            System.Array values = (Array)rang.Cells.Value2;
            //打开文件
            FileStream aFile = new FileStream(Application.StartupPath + "//err.ini", FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(aFile);
            //处理数据
            for (int i = 2; i < values.GetLength(0); i++)
            {
                if (values.GetValue(i, 1) == null || values.GetValue(i, 2) == null)
                {
                    //两者皆不为null
                    continue;
                }
                var number = values.GetValue(i,1).ToString();
                var money = values.GetValue(i,2).ToString();
                
                //判断是否可以转化为数字
                try
                {
                    var testMoney = Convert.ToDouble(money);
                    var err = DataBase.getInstance().updateUserMoney(number, money);
                    if (err == DataBase.Error.手机号不存在)
                    {
                        sw.WriteLine(number);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("导入手机号为"+number+"的用户余额时出错=>"+ex.Message);
                }
            }
            sw.Flush();
            sw.Close();
            aFile.Close();
            excelApp.Quit();
            excelApp = null;
            MessageBox.Show("所有余额导入成功!");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            通用查询窗口 t = new 通用查询窗口();
            t.Show();
        }

    }
}
